/**
 * 游戏Agent React Hook
 * 为React组件提供便捷的AI Agent交互接口
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import { 
  gameClient, 
  GameConfig, 
  ChatRequest, 
  DeductionSubmission, 
  GameAgentResponse 
} from '../agents/mastra-integration';

/**
 * 游戏状态接口
 */
export interface GameState {
  sessionId?: string;
  phase: 'idle' | 'initializing' | 'investigation' | 'deduction' | 'completed' | 'paused' | 'error';
  difficulty?: 'easy' | 'normal' | 'hard';
  theme?: string;
  suspectCount?: number;
  timeRemaining?: number;
  score?: number;
  discoveredClues?: string[];
  conversationCount?: number;
  suspectInteractions?: Record<string, number>;
  caseData?: any;
  lastError?: string;
}

/**
 * Hook状态接口
 */
interface UseGameAgentState {
  gameState: GameState;
  isLoading: boolean;
  error: string | null;
  lastResponse: GameAgentResponse | null;
}

/**
 * Hook返回值接口
 */
interface UseGameAgentReturn extends UseGameAgentState {
  // 游戏控制方法
  startNewGame: (config: GameConfig) => Promise<GameAgentResponse>;
  pauseGame: () => Promise<GameAgentResponse>;
  resumeGame: () => Promise<GameAgentResponse>;
  endGame: () => Promise<GameAgentResponse>;
  
  // 游戏交互方法
  chatWithSuspect: (suspectId: string, question: string) => Promise<GameAgentResponse>;
  submitDeduction: (submission: Omit<DeductionSubmission, 'sessionId'>) => Promise<GameAgentResponse>;
  getGameStatus: () => Promise<GameAgentResponse>;
  
  // 状态管理方法
  clearError: () => void;
  resetGame: () => void;
  updateGameState: (updates: Partial<GameState>) => void;
}

/**
 * 游戏Agent Hook
 * 提供完整的游戏AI交互功能
 */
export function useGameAgent(): UseGameAgentReturn {
  // 状态管理
  const [state, setState] = useState<UseGameAgentState>({
    gameState: {
      phase: 'idle'
    },
    isLoading: false,
    error: null,
    lastResponse: null
  });

  // 对话历史记录
  const conversationHistory = useRef<Map<string, Array<{
    role: 'user' | 'assistant';
    content: string;
    timestamp: string;
  }>>>(new Map());

  // 更新状态的辅助函数
  const updateState = useCallback((updates: Partial<UseGameAgentState>) => {
    setState(prev => ({ ...prev, ...updates }));
  }, []);

  // 更新游戏状态的辅助函数
  const updateGameState = useCallback((updates: Partial<GameState>) => {
    setState(prev => ({
      ...prev,
      gameState: { ...prev.gameState, ...updates }
    }));
  }, []);

  // 处理Agent响应的通用函数
  const handleAgentResponse = useCallback((response: GameAgentResponse) => {
    updateState({
      lastResponse: response,
      error: response.success ? null : response.message,
      isLoading: false
    });

    if (response.success && response.gameState) {
      updateGameState(response.gameState);
    }

    return response;
  }, [updateState, updateGameState]);

  // 开始新游戏
  const startNewGame = useCallback(async (config: GameConfig): Promise<GameAgentResponse> => {
    updateState({ isLoading: true, error: null });
    updateGameState({ phase: 'initializing' });

    try {
      console.log('🎮 Hook: 开始新游戏', config);
      const response = await gameClient.startNewGame(config);
      
      if (response.success && response.data) {
        updateGameState({
          sessionId: response.data.sessionId,
          phase: 'investigation',
          difficulty: config.difficulty,
          theme: config.theme,
          suspectCount: config.suspectCount,
          caseData: response.data.caseData,
          timeRemaining: response.gameState?.timeRemaining || 300,
          score: 0,
          discoveredClues: [],
          conversationCount: 0,
          suspectInteractions: {}
        });

        // 清空对话历史
        conversationHistory.current.clear();
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `开始游戏失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [updateState, updateGameState, handleAgentResponse]);

  // 与嫌疑人对话
  const chatWithSuspect = useCallback(async (suspectId: string, question: string): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });

    try {
      console.log('💬 Hook: 与嫌疑人对话', { suspectId, question });
      
      // 获取对话历史
      const history = conversationHistory.current.get(suspectId) || [];
      
      const chatRequest: ChatRequest = {
        sessionId: state.gameState.sessionId,
        suspectId,
        question,
        conversationHistory: history
      };

      const response = await gameClient.chatWithSuspect(chatRequest);

      if (response.success) {
        // 更新对话历史
        const newHistory = [
          ...history,
          {
            role: 'user' as const,
            content: question,
            timestamp: new Date().toISOString()
          },
          {
            role: 'assistant' as const,
            content: response.data?.response || response.message,
            timestamp: new Date().toISOString()
          }
        ];
        conversationHistory.current.set(suspectId, newHistory);

        // 更新游戏状态
        updateGameState({
          conversationCount: (state.gameState.conversationCount || 0) + 1,
          suspectInteractions: {
            ...state.gameState.suspectInteractions,
            [suspectId]: (state.gameState.suspectInteractions?.[suspectId] || 0) + 1
          }
        });
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `对话失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, state.gameState.conversationCount, state.gameState.suspectInteractions, updateState, updateGameState, handleAgentResponse]);

  // 提交推理结果
  const submitDeduction = useCallback(async (submission: Omit<DeductionSubmission, 'sessionId'>): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });
    updateGameState({ phase: 'deduction' });

    try {
      console.log('🔍 Hook: 提交推理结果', submission);
      
      const deductionSubmission: DeductionSubmission = {
        ...submission,
        sessionId: state.gameState.sessionId
      };

      const response = await gameClient.submitDeduction(deductionSubmission);

      if (response.success) {
        updateGameState({
          phase: 'completed',
          score: response.data?.score || state.gameState.score
        });
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `提交推理失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, state.gameState.score, updateState, updateGameState, handleAgentResponse]);

  // 获取游戏状态
  const getGameStatus = useCallback(async (): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });

    try {
      console.log('📊 Hook: 获取游戏状态');
      const response = await gameClient.getGameStatus(state.gameState.sessionId);
      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `获取状态失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, updateState, handleAgentResponse]);

  // 暂停游戏
  const pauseGame = useCallback(async (): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });

    try {
      console.log('⏸️ Hook: 暂停游戏');
      const response = await gameClient.pauseGame(state.gameState.sessionId);
      
      if (response.success) {
        updateGameState({ phase: 'paused' });
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `暂停游戏失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, updateState, updateGameState, handleAgentResponse]);

  // 恢复游戏
  const resumeGame = useCallback(async (): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });

    try {
      console.log('▶️ Hook: 恢复游戏');
      const response = await gameClient.resumeGame(state.gameState.sessionId);
      
      if (response.success) {
        updateGameState({ phase: 'investigation' });
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `恢复游戏失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, updateState, updateGameState, handleAgentResponse]);

  // 结束游戏
  const endGame = useCallback(async (): Promise<GameAgentResponse> => {
    if (!state.gameState.sessionId) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: '没有活跃的游戏会话',
        error: 'NO_SESSION'
      };
      return handleAgentResponse(errorResponse);
    }

    updateState({ isLoading: true, error: null });

    try {
      console.log('🏁 Hook: 结束游戏');
      const response = await gameClient.endGame(state.gameState.sessionId);
      
      if (response.success) {
        updateGameState({ phase: 'completed' });
      }

      return handleAgentResponse(response);
    } catch (error) {
      const errorResponse: GameAgentResponse = {
        success: false,
        message: `结束游戏失败: ${error instanceof Error ? error.message : '未知错误'}`,
        error: 'HOOK_ERROR'
      };
      return handleAgentResponse(errorResponse);
    }
  }, [state.gameState.sessionId, updateState, updateGameState, handleAgentResponse]);

  // 清除错误
  const clearError = useCallback(() => {
    updateState({ error: null });
  }, [updateState]);

  // 重置游戏
  const resetGame = useCallback(() => {
    setState({
      gameState: { phase: 'idle' },
      isLoading: false,
      error: null,
      lastResponse: null
    });
    conversationHistory.current.clear();
  }, []);

  // 自动保存游戏状态到localStorage
  useEffect(() => {
    if (state.gameState.sessionId && state.gameState.phase !== 'idle') {
      localStorage.setItem('cyberDetectiveGameState', JSON.stringify(state.gameState));
    }
  }, [state.gameState]);

  // 从localStorage恢复游戏状态
  useEffect(() => {
    const savedState = localStorage.getItem('cyberDetectiveGameState');
    if (savedState) {
      try {
        const parsedState = JSON.parse(savedState);
        if (parsedState.sessionId && parsedState.phase !== 'completed') {
          updateGameState(parsedState);
        }
      } catch (error) {
        console.warn('恢复游戏状态失败:', error);
      }
    }
  }, [updateGameState]);

  return {
    ...state,
    startNewGame,
    pauseGame,
    resumeGame,
    endGame,
    chatWithSuspect,
    submitDeduction,
    getGameStatus,
    clearError,
    resetGame,
    updateGameState
  };
}
